import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { fileURLToPath, URL } from 'node:url';
import UnoCss from 'unocss/vite';
import AutoImport from 'unplugin-auto-import/vite';
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers';
import Components from 'unplugin-vue-components/vite';
import { VueRouterAutoImports, getPascalCaseRouteName } from 'unplugin-vue-router';
import VueRouter from 'unplugin-vue-router/vite';
import { defineConfig, loadEnv } from 'vite';
import { ClientSideLayout } from 'vite-plugin-vue-layouts';

export default defineConfig(({ mode }) => {
  const envDir = fileURLToPath(new URL('./env_config', import.meta.url));

  const env = loadEnv(mode, envDir) as ImportMetaEnv;

  return {
    envDir,
    build: {
      outDir: fileURLToPath(new URL('./dist/' + env.VITE_DIST_DIR, import.meta.url)),
    },
    plugins: [
      VueRouter({
        dts: './src/types/typed-router.d.ts',
        getRouteName: getPascalCaseRouteName,
        // 排除所有以__开头的文件和文件夹，以及components文件夹下的所有文件和文件夹
        exclude: ['**/__*', '**/__*/**/*', '**/components/**/*'],
        importMode: 'async',
      }),
      vue(),
      vueJsx(),
      ClientSideLayout({
        layoutsDirs: 'src/layouts',
        pagesDirs: 'src/pages',
        exclude: ['**/__*__.vue', '**/__*.vue', '**/components/**/*', '**/nav/**/*'],
      }),
      UnoCss(),
      AutoImport({
        dts: './src/types/auto-imports.d.ts',
        imports: [
          'vue',
          VueRouterAutoImports,
          'pinia',
          { dayjs: [['*', 'dayjs']] },
          {
            from: 'dayjs',
            imports: ['Dayjs'],
            type: true,
          },
        ],
        dirs: ['./src/utils/router', './src/utils/axios'],
      }),
      Components({
        dts: './src/types/components.d.ts',
        resolvers: [
          AntDesignVueResolver({
            importStyle: false,
          }),
        ],
      }),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    optimizeDeps: {
      include: ['ant-design-vue/es', 'vue', 'vue-router', 'pinia', 'lodash-es', 'dayjs'],
    },
    server: {
      proxy: {
        '/api': {
          target: env.VITE_BASE_API,
          changeOrigin: true,
          rewrite(path) {
            return path.replace(/^\/api/, '');
          },
        },
      },
    },
  };
});
